package com.nforce.linremote;

import java.util.HashSet;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.nforce.linremote.EditDialogFragment.NoticeDialogListener;
import com.nforce.linremote.networking.SessionUtils;
import com.nforce.linremote.scripting.ContextHolder;

public class StartActivity extends FragmentActivity implements NoticeDialogListener {

    private String mIp;

    private ArrayAdapter<String> adapter;

    private Spinner mAddressSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	ContextHolder.setContext(getApplicationContext());

	setContentView(R.layout.activity_start);

	mAddressSpinner = (Spinner) findViewById(R.id.address_spinner);

	SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
	Set<String> ipSet = p.getStringSet(Constants.KEY_PREF_FAVS, new HashSet<String>());

	adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	if (ipSet != null) {
	    for (String s : ipSet) {
		adapter.add(s);
	    }
	}
	adapter.add(getString(R.string.custom));
	mAddressSpinner.setAdapter(adapter);
	mAddressSpinner.setOnLongClickListener(new OnLongClickListener() {

	    @Override
	    public boolean onLongClick(View v) {
		EditDialogFragment dialog = new EditDialogFragment();

		Bundle arg = new Bundle();
		arg.putString(Constants.EXTRA_IP_ADDRESS, (String) mAddressSpinner.getSelectedItem());
		dialog.setArguments(arg);
		dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
		return true;
	    }
	});
	mAddressSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		int count = parent.getCount();
		if (pos == count - 1) {
		    EditDialogFragment dialog = new EditDialogFragment();
		    dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
		}
	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> arg0) {
	    }
	});

	findViewById(R.id.connect_button).setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View view) {
		connect();
	    }
	});

	findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View view) {
		scan();
	    }
	});
    }

    @Override
    protected void onResume() {
	super.onResume();
	disconnect();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	super.onCreateOptionsMenu(menu);
	getMenuInflater().inflate(R.menu.simple_menu, menu);
	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.menu_settings:
		Intent intent = new Intent(this, SettingsActivity.class);
		startActivity(intent);
		return true;
	}
	return super.onOptionsItemSelected(item);
    }

    public void disconnect() {
	AsyncTask<Void, Void, Void> callJob = new AsyncTask<Void, Void, Void>() {

	    @Override
	    protected Void doInBackground(Void... params) {
		SessionUtils.terminateSession();
		return null;
	    }
	};
	callJob.execute((Void) null);
    }

    public void scan() {
	if (!wifiConnected()) {
	    return;
	}
	Intent intent = new Intent(this, ListHostsActivity.class);
	intent.putExtra(Constants.EXTRA_LIST_HOSTS, Constants.MESSAGE_SCAN);
	startActivity(intent);
    }

    public void connect() {
	if (!wifiConnected()) {
	    return;
	}

	mIp = (String) mAddressSpinner.getSelectedItem();

	Intent intent = new Intent(this, ListHostsActivity.class);
	intent.putExtra(Constants.EXTRA_LIST_HOSTS, Constants.MESSAGE_CONNECT);
	intent.putExtra(Constants.EXTRA_IP_ADDRESS, mIp);
	startActivity(intent);
    }

    private boolean wifiConnected() {
	ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

	NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
	if (networkInfo != null) {
	    if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
		return true;
	    }
	}

	startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
	return false;
    }

    @Override
    public void onDialogPositiveClick(String address) {
	int selected = mAddressSpinner.getSelectedItemPosition();
	if (selected != mAddressSpinner.getCount() - 1) {
	    adapter.remove((String) mAddressSpinner.getSelectedItem());
	}
	adapter.insert(address, 0);
	mAddressSpinner.setSelection(0, true);
    }
}